import editor from "./editor";
import domUtils from "./core/domUtils";
import dtd from "./core/dtd";
import browser, { ie } from './core/browser';
function getObj(editor, tagNames) {
    return domUtils.filterNodeList(
        editor.selection.getStartElementPath(),
        tagNames
    );
}
function execCommand(cmdName) {
    console.log("execCommand", cmdName)
    if (cmdName == "red") {
        markRed();
    }


    if (cmdName == "bold") {
        markBold();
    }

    if (cmdName == "removeFormat") {
        removeFormat();
    }


    if (cmdName == "number") {
        markNumber();
    }

}


function markRed() {
    const selection = editor.selection;;
    const range = selection.getRange();
    const tagNames = ['red', 'r']
    const cmdName = "red";
    const obj = getObj(editor, tagNames);
    if (range.collapsed) {
        // if (obj) {
        //     var tmpText = me.document.createTextNode("");
        //     range.insertNode(tmpText).removeInlineStyle(tagNames);
        //     range.setStartBefore(tmpText);
        //     domUtils.remove(tmpText);
        // }
        // else {
        //     var tmpNode = range.document.createElement(tagNames[0]);
        //     if (cmdName == "superscript" || cmdName == "subscript") {
        //         tmpText = me.document.createTextNode("");
        //         range
        //             .insertNode(tmpText)
        //             .removeInlineStyle(["sub", "sup"])
        //             .setStartBefore(tmpText)
        //             .collapse(true);
        //     }
        //     range.insertNode(tmpNode).setStart(tmpNode, 0);
        // }
    }
    else {
        if (cmdName == "superscript" || cmdName == "subscript") {
            if (!obj || obj.tagName.toLowerCase() != cmdName) {
                range.removeInlineStyle(["sub", "sup"]);
            }
        }
        obj
            ? range.removeInlineStyle(tagNames)
            : range.applyInlineStyle(tagNames[0]);
    }
    // range.select();  
}


function markBold() {
    const selection = editor.selection;;
    const range = selection.getRange();
    const tagNames = ['bold', 'b']
    const cmdName = "bold";
    const obj = getObj(editor, tagNames);  
        if (cmdName == "superscript" || cmdName == "subscript") {
            if (!obj || obj.tagName.toLowerCase() != cmdName) {
                range.removeInlineStyle(["sub", "sup"]);
            }
        }
        obj
            ? range.removeInlineStyle(tagNames)
            : range.applyInlineStyle(tagNames[0]);
    
    // range.select();  
}

function markNumber() {
    const selection = editor.selection;;
    const range = selection.getRange();
    const tagNames = ['number', 'n']
    const cmdName = "number";
    const obj = getObj(editor, tagNames);
    if (range.collapsed) {
    }
    else {
        obj
            ? range.removeInlineStyle(tagNames)
            : range.applyInlineStyle(tagNames[0]);
    }
    // range.select();  
}

function removeFormat() {
    var notIncludeA = true;
    var style = false;
    const removeFormatTags = "b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var,red,number,bold";
    const removeFormatAttributes = "class,style,lang,width,height,align,hspace,valign";

    var tagReg = new RegExp(
        "^(?:" +
        (removeFormatTags).replace(/,/g, "|") +
        ")$",
        "i"
    ),
        bookmark,
        node,
        parent,
        filter = function (node) {
            return node.nodeType == 1;
        };

    function isRedundantSpan(node) {
        if (node.nodeType == 3 || node.tagName.toLowerCase() != "span") {
            return 0;
        }
        if (browser.ie) {
            //ie 下判断实效，所以只能简单用style来判断
            //return node.style.cssText == '' ? 1 : 0;
            var attrs = node.attributes;
            if (attrs.length) {
                for (var i = 0, l = attrs.length; i < l; i++) {
                    if (attrs[i].specified) {
                        return 0;
                    }
                }
                return 1;
            }
        }
        return !node.attributes.length;
    }

    function doRemove(range) {
        var bookmark1 = range.createBookmark();
        if (range.collapsed) {
            range.enlarge(true);
        }

        //不能把a标签切了
        if (!notIncludeA) {
            var aNode = domUtils.findParentByTagName(
                range.startContainer,
                "a",
                true
            );
            if (aNode) {
                range.setStartBefore(aNode);
            }

            aNode = domUtils.findParentByTagName(range.endContainer, "a", true);
            if (aNode) {
                range.setEndAfter(aNode);
            }
        }

        bookmark = range.createBookmark();

        node = bookmark.start;

        //切开始
        while ((parent = node.parentNode) && !domUtils.isBlockElm(parent)) {
            domUtils.breakParent(node, parent);

            domUtils.clearEmptySibling(node);
        }
        if (bookmark.end) {
            //切结束
            node = bookmark.end;
            while ((parent = node.parentNode) && !domUtils.isBlockElm(parent)) {
                domUtils.breakParent(node, parent);
                domUtils.clearEmptySibling(node);
            }

            //开始去除样式
            var current = domUtils.getNextDomNode(bookmark.start, false, filter),
                next;
            while (current) {
                if (current == bookmark.end) {
                    break;
                }

                next = domUtils.getNextDomNode(current, true, filter);

                if (
                    !dtd.$empty[current.tagName.toLowerCase()] &&
                    !domUtils.isBookmarkNode(current)
                ) {
                    console.log("tagReg", tagReg, current.tagName, tagReg.test(current.tagName));
                    if (tagReg.test(current.tagName)) {
                        if (style) {
                            domUtils.removeStyle(current, style);
                            console.log(isRedundantSpan(current))
                            if (isRedundantSpan(current) && style != "text-decoration") {
                                domUtils.remove(current, true);
                            }
                        } else {
                            domUtils.remove(current, true);
                        }
                    } else {
                        //trace:939  不能把list上的样式去掉
                        if (
                            !dtd.$tableContent[current.tagName] &&
                            !dtd.$list[current.tagName]
                        ) {
                            domUtils.removeAttributes(current, removeFormatAttributes);
                            if (isRedundantSpan(current)) {
                                domUtils.remove(current, true);
                            }
                        }
                    }
                }
                current = next;
            }
        }
        //trace:1035
        //trace:1096 不能把td上的样式去掉，比如边框
        var pN = bookmark.start.parentNode;
        if (
            domUtils.isBlockElm(pN) &&
            !dtd.$tableContent[pN.tagName] &&
            !dtd.$list[pN.tagName]
        ) {
            domUtils.removeAttributes(pN, removeFormatAttributes);
        }
        pN = bookmark.end.parentNode;
        if (
            bookmark.end &&
            domUtils.isBlockElm(pN) &&
            !dtd.$tableContent[pN.tagName] &&
            !dtd.$list[pN.tagName]
        ) {
            domUtils.removeAttributes(pN, removeFormatAttributes);
        }
        range.moveToBookmark(bookmark).moveToBookmark(bookmark1);
        //清除冗余的代码 <b><bookmark></b>
        var node = range.startContainer,
            tmp,
            collapsed = range.collapsed;
        while (
            node.nodeType == 1 &&
            domUtils.isEmptyNode(node) &&
            dtd.$removeEmpty[node.tagName]
        ) {
            tmp = node.parentNode;
            range.setStartBefore(node);
            //trace:937
            //更新结束边界
            if (range.startContainer === range.endContainer) {
                range.endOffset--;
            }
            domUtils.remove(node);
            node = tmp;
        }

        if (!collapsed) {
            node = range.endContainer;
            while (
                node.nodeType == 1 &&
                domUtils.isEmptyNode(node) &&
                dtd.$removeEmpty[node.tagName]
            ) {
                tmp = node.parentNode;
                range.setEndBefore(node);
                domUtils.remove(node);

                node = tmp;
            }
        }
    }

    var range = editor.selection.getRange();
    if (!range.collapsed) {
        doRemove(range);
        //range.select();
    }

}

var data = '中国<red>高速免费结束<number>收全程费3424元用</number>，</red>司机大<red><number>闹收费站：1</number>契约精神</red>的缺失'
let current = 0;
let match;
let lastTextPos = 0;
const kMarkupPattern = /<[^>]+>/g


const reg = new RegExp("<number>(.*?)</number>", "g")
const result = data.match(reg);

if (result && result.length > 0) {
   const props =  result.map((item) => {
        return item.replace(reg, function (match, p1, offset, string) {
            return p1;
        })
    })

    console.log(props)
}



data = data.replace(reg, function (match, p1, offset, string) {
    console.log(p1)
    return p1;
});

console.log(data)   
// while (match = kMarkupPattern.exec(data)) {
//     let { 0: matchText, index } = match;
//     console.log(matchText, index)
//     if (matchText == "<red>") {
//         if (index > lastTextPos) {
//             result.push({
//                 tag: "",
//                 text: data.substring(lastTextPos, index)
//             }
//             );
//         }
//         lastTextPos = index + matchText.length;
//     }
//     else if (matchText == "</red>") {
//         result.push({
//             tag: "red",
//             text: data.substring(lastTextPos, index)
//         });
//         lastTextPos = index + matchText.length;
//     }
// }

// if (lastTextPos < data.length) {
//     result.push({
//         tag: "",
//         text: data.substring(lastTextPos)
//     });
// }



// console.log(result)



// const htmlString = '<div>Content</div><p>More content</p>';
// const tagRegex = /<\/?[\w\s="/.':;#-\/\?]+>/gi;

// const matchedTags = htmlString.match(tagRegex);

// console.log(matchedTags);
// console.log("result", str.split(/<[^>]+>/g))

window.execCommand = execCommand;